package com.wss.lsl.security.crypto.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyStore;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

/**
 * 初始化SSLContext，构建https连接
 * 
 * @author sean
 * 
 */
public class SSLContextDemo {

	public KeyStore getKeyStore(String keyStorePath, String password)
			throws Exception {

		FileInputStream fis = new FileInputStream(new File(keyStorePath));
		KeyStore ks = KeyStore.getInstance("JKS");
		ks.load(fis, password.toCharArray());

		fis.close();

		return ks;
	}

	public SSLSocketFactory getSslSocketFactory(String keyStorePath,
			String trustStorePath, String password) throws Exception {

		KeyManagerFactory keyManagerFactory = KeyManagerFactory
				.getInstance("SunX509");
		TrustManagerFactory trustManagerFactory = TrustManagerFactory
				.getInstance("SunX509");
		keyManagerFactory.init(getKeyStore(keyStorePath, password),
				password.toCharArray());
		trustManagerFactory.init(getKeyStore(trustStorePath, password));

		SSLContext sslContext = SSLContext.getInstance("SSL");
		sslContext.init(keyManagerFactory.getKeyManagers(),
				trustManagerFactory.getTrustManagers(), null);

		SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

		return sslSocketFactory;
	}

	/**
	 * 执行https请求
	 * 
	 * @param url
	 * @throws Exception
	 */
	@SuppressWarnings("unused")
	public void processHttps(String httpsUrl) throws Exception {
		// 客户端没有证书不需要
		String keyStorePath = "";
		String trustStorePath = "";
		String password = "password";

		URL url = new URL(httpsUrl);
		HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
		conn.setDoInput(true);
		conn.setDoOutput(true);

		// SSLSocketFactory sslSocketFactory = getSslSocketFactory(keyStorePath,
		// trustStorePath, password);
		// conn.setSSLSocketFactory(sslSocketFactory);

		// 读取内容
		InputStream is = conn.getInputStream();
		int length = conn.getContentLength();
		if (length > 0) {
			byte[] bytes = new byte[length];
			is.read(bytes);
			System.out.println(new String(bytes, "UTF-8"));
		}

		is.close();
	}
}
